package com.lambkit.plugin.xxljob;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ClassUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.log.Log;
import com.lambkit.core.Lambkit;
import com.lambkit.core.LifecycleException;
import com.lambkit.core.plugin.Plugin;
import com.lambkit.core.service.ScanClassProcess;
import com.xxl.job.core.executor.impl.XxlJobSimpleExecutor;

import java.util.List;
import java.util.Set;

/**
 * @author yangyong(孤竹行)
 */
public class XxljobLambkitPlugin extends Plugin {

    private static Log logger = Log.get(XxljobLambkitPlugin.class);

    private XxlJobSimpleExecutor xxlJobExecutor = null;

    @Override
    public void start() throws LifecycleException {
        xxlJobExecutor = new XxlJobSimpleExecutor();
        XxljobConfig xxljobConfig= Lambkit.get(XxljobConfig.class);
        xxlJobExecutor.setAdminAddresses(xxljobConfig.getAdminAddresses());
        xxlJobExecutor.setAccessToken(xxljobConfig.getAccessToken());
        xxlJobExecutor.setAppname(xxljobConfig.getAppname());
        xxlJobExecutor.setAddress(xxljobConfig.getAddress());
        xxlJobExecutor.setIp(xxljobConfig.getIp());
        xxlJobExecutor.setPort(xxljobConfig.getPort());
        xxlJobExecutor.setLogPath(xxljobConfig.getLogpath());
        xxlJobExecutor.setLogRetentionDays(xxljobConfig.getLogretentiondays());

        // registry job bean
        String scanPackage = xxljobConfig.getScanPackage();
        if(StrUtil.isBlank(scanPackage)) {
            Class targetClass = Lambkit.context().getTargetClass();
            if(targetClass!=null) {
                scanPackage = ClassUtil.getPackage(targetClass);
            }
        }
        List<Object> xxlJobBeanList = CollUtil.newArrayList();
        Lambkit.context().classOperateService().scanPackageByAnnotation(scanPackage, XxljobBean.class, new ScanClassProcess() {
            @Override
            public void process(Class<?> clazz) {
                System.out.println("clazz:" + clazz.getName());
                XxljobBean xxljobBean = clazz.getAnnotation(XxljobBean.class);
                if(xxljobBean!=null) {
                    xxlJobBeanList.add(Lambkit.get(clazz));
                }
            }
        });
        xxlJobExecutor.setXxlJobBeanList(xxlJobBeanList);

        // start executor
        try {
            xxlJobExecutor.start();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }

    @Override
    public void stop() throws LifecycleException {
        super.stop();
        if (xxlJobExecutor != null) {
            xxlJobExecutor.destroy();
        }
    }
}
